<template>
  <div class="feature-submit-container">
    <div class="feature-submit-header">
      <n-breadcrumb>
        <n-breadcrumb-item>
          <router-link to="/">首页</router-link>
        </n-breadcrumb-item>
        <n-breadcrumb-item>
          <router-link :to="{name: 'feature-requests'}">功能请求</router-link>
        </n-breadcrumb-item>
        <n-breadcrumb-item>提交新请求</n-breadcrumb-item>
      </n-breadcrumb>
      
      <h1 class="feature-submit-title">提交功能请求</h1>
      <p class="feature-submit-subtitle">分享您希望在系统中看到的功能或改进建议</p>
    </div>
    
    <div class="feature-submit-body">
      <n-card class="submit-form-card">
        <n-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-placement="top"
          require-mark-placement="right-hanging"
          size="medium"
          :disabled="loading"
        >
          <n-form-item path="title" label="标题">
            <n-input 
              v-model:value="formData.title" 
              placeholder="请输入功能请求标题（简洁明了）" 
              maxlength="100"
              show-count
              clearable
            />
          </n-form-item>
          
          <n-form-item path="description" label="详细描述">
            <n-input 
              v-model:value="formData.description" 
              type="textarea" 
              placeholder="请详细描述您需要的功能、解决的问题以及期望的效果" 
              :rows="8"
              maxlength="5000"
              show-count
            />
          </n-form-item>
          
          <n-form-item path="is_anonymous">
            <n-checkbox v-model:checked="formData.is_anonymous">
              匿名提交
            </n-checkbox>
          </n-form-item>
          
          <!-- 匿名且未保存名称时显示输入框，已保存时显示只读 -->
          <n-form-item v-if="!isLogin && !savedCustomName" path="custom_name" label="您的名称">
            <n-input v-model:value="formData.custom_name" placeholder="请输入2-20个字符的名称" maxlength="20" />
          </n-form-item>
          <n-form-item v-else-if="!isLogin && savedCustomName" label="您的名称">
            <n-input :value="savedCustomName" readonly />
          </n-form-item>
          
          <div class="form-tips">
            <n-alert type="info" title="提示">
              <p>1. 请确保您的请求内容不包含敏感或违规信息</p>
              <p>2. 提交后需要管理员审核才会公开显示</p>
              <p>3. 相似的功能请求可能会被合并</p>
            </n-alert>
          </div>
          
          <div class="form-actions">
            <n-space justify="end">
              <n-button @click="$router.push({name: 'feature-requests'})">
                取消
              </n-button>
              <n-button 
                type="primary" 
                :loading="loading" 
                :disabled="loading"
                @click="handleSubmit"
              >
                提交请求
              </n-button>
            </n-space>
          </div>
        </n-form>
      </n-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { NAlert, NBreadcrumb, NBreadcrumbItem, NButton, NCard, NCheckbox, NForm, NFormItem, NInput, NSpace } from 'naive-ui'
import { submitFeatureRequest } from '@/api/feature'
import { FeatureRequestSubmitParams } from '@/api/types/feature'

// 创建消息提示
const message = useMessage()
const router = useRouter()
const formRef = ref(null)

// 加载状态
const loading = ref(false)

// 表单数据
const formData = reactive<FeatureRequestSubmitParams>({
  title: '',
  description: '',
  is_anonymous: false,
  custom_name: '' // 新增：自定义名称字段
})

// 是否已登录（此处假设有全局auth对象或方法，实际项目请替换）
const isLogin = computed(() => {
  // 这里请根据实际登录状态实现
  // 例如：return !!store.state.user.id
  return false // 默认未登录，需替换
})

// 本地存储的自定义名称key
const CUSTOM_NAME_KEY = 'feature_custom_name'

// 本地已保存的自定义名称
const savedCustomName = ref<string | null>(null)

// 自定义名称输入校验规则
const customNameRule = [
  { required: true, message: '请输入您的名称', trigger: 'blur' },
  { min: 2, max: 20, message: '名称长度需在2-20个字符之间', trigger: 'blur' }
]

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入功能请求标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度需在5-100个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入功能描述', trigger: 'blur' },
    { min: 20, max: 5000, message: '描述长度需在20-5000个字符之间', trigger: 'blur' }
  ],
  // 仅未登录且未保存名称时校验custom_name
  ...(isLogin.value || savedCustomName.value ? {} : { custom_name: customNameRule })
}

// 组件挂载时读取本地自定义名称
onMounted(() => {
  const name = localStorage.getItem(CUSTOM_NAME_KEY)
  if (name) {
    savedCustomName.value = name
    formData.custom_name = name
  }
})

// 提交表单
const handleSubmit = () => {
  if (!formRef.value) return
  
  // 未登录且未保存名称时，需校验自定义名称
  if (!isLogin.value && !savedCustomName.value) {
    if (!formData.custom_name || formData.custom_name.length < 2 || formData.custom_name.length > 20) {
      return message.error('请填写2-20个字符的自定义名称')
    }
  }
  
  (formRef.value as any).validate(async (errors: any) => {
    if (errors) {
      return message.error('请填写完整有效的信息')
    }
    
    // 未登录且本地无名称时，保存自定义名称到localStorage
    if (!isLogin.value && !savedCustomName.value && formData.custom_name) {
      localStorage.setItem(CUSTOM_NAME_KEY, formData.custom_name)
      savedCustomName.value = formData.custom_name
    }
    
    loading.value = true
    
    try {
      const response = await submitFeatureRequest(formData)
      
      if (response.code === 1) {
        message.success('功能请求提交成功')
        
        // 检查响应中是否包含id
        const responseData = response.data as any; // 使用类型断言
        if (responseData && responseData.id) {
          // 提交成功，跳转到详情页
          router.push({
            name: 'feature-detail', 
            params: { id: responseData.id }
          })
        } else {
          // 如果没有返回ID，跳转到列表页
          router.push({ name: 'feature-requests' })
        }
      } else {
        message.error(response.message || '提交失败')
      }
    } catch (error) {
      console.error('提交功能请求失败:', error)
      message.error('提交功能请求失败，请稍后重试')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
.feature-submit-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.feature-submit-header {
  margin-bottom: 2rem;
}

.feature-submit-title {
  font-size: 2rem;
  font-weight: 700;
  color: var(--n-text-color-1);
  margin: 1.5rem 0 0.5rem;
}

.feature-submit-subtitle {
  font-size: 1.125rem;
  color: var(--n-text-color-2);
  margin-bottom: 1.5rem;
}

.feature-submit-body {
  margin-bottom: 2rem;
}

.submit-form-card {
  padding: 1rem;
}

.form-tips {
  margin: 1.5rem 0;
}

.form-actions {
  margin-top: 2rem;
}
</style> 